import { useState } from 'react';
import { Input, Modal, Tabs, List, Input as AntInput } from 'antd';
import { useSelector } from 'react-redux';
import * as Icons from '@ant-design/icons';
import DynamicIcon from './DynamicIcon';

const { Search } = AntInput;

// 方向图标
const directionIcons = [
  'StepBackwardOutlined',
  'StepForwardOutlined',
  'FastBackwardOutlined',
  'FastForwardOutlined',
  'ShrinkOutlined',
  'ArrowsAltOutlined',
  'DownOutlined',
  'UpOutlined',
  'LeftOutlined',
  'RightOutlined',
  'CaretUpOutlined',
  'CaretDownOutlined',
  'CaretLeftOutlined',
  'CaretRightOutlined',
  'UpCircleOutlined',
  'DownCircleOutlined',
  'LeftCircleOutlined',
  'RightCircleOutlined',
  'DoubleRightOutlined',
  'DoubleLeftOutlined',
  'VerticalLeftOutlined',
  'VerticalRightOutlined',
  'VerticalAlignTopOutlined',
  'VerticalAlignMiddleOutlined',
  'VerticalAlignBottomOutlined',
  'ForwardOutlined',
  'BackwardOutlined',
  'RollbackOutlined',
  'EnterOutlined',
  'RetweetOutlined',
  'SwapOutlined',
  'SwapLeftOutlined',
  'SwapRightOutlined',
  'ArrowUpOutlined',
  'ArrowDownOutlined',
  'ArrowLeftOutlined',
  'ArrowRightOutlined',
  'PlayCircleOutlined',
  'UpSquareOutlined',
  'DownSquareOutlined',
  'LeftSquareOutlined',
  'RightSquareOutlined',
  'LoginOutlined',
  'LogoutOutlined',
  'MenuFoldOutlined',
  'MenuUnfoldOutlined',
  'BorderBottomOutlined',
  'BorderHorizontalOutlined',
  'BorderInnerOutlined',
  'BorderOuterOutlined',
  'BorderLeftOutlined',
  'BorderRightOutlined',
  'BorderTopOutlined',
  'BorderVerticleOutlined',
  'PicCenterOutlined',
  'PicLeftOutlined',
  'PicRightOutlined',
  'RadiusBottomleftOutlined',
  'RadiusBottomrightOutlined',
  'RadiusUpleftOutlined',
  'RadiusUprightOutlined',
  'FullscreenOutlined',
  'FullscreenExitOutlined'
];

// 建议图标
const suggestionIcons = [
  'QuestionOutlined',
  'QuestionCircleOutlined',
  'PlusOutlined',
  'PlusCircleOutlined',
  'PauseOutlined',
  'PauseCircleOutlined',
  'MinusOutlined',
  'MinusCircleOutlined',
  'PlusSquareOutlined',
  'MinusSquareOutlined',
  'InfoOutlined',
  'InfoCircleOutlined',
  'ExclamationOutlined',
  'ExclamationCircleOutlined',
  'CloseOutlined',
  'CloseCircleOutlined',
  'CloseSquareOutlined',
  'CheckOutlined',
  'CheckCircleOutlined',
  'CheckSquareOutlined',
  'ClockCircleOutlined',
  'WarningOutlined',
  'IssuesCloseOutlined',
  'StopOutlined'
];

// 编辑器图标
const editorIcons = [
  'EditOutlined',
  'FormOutlined',
  'CopyOutlined',
  'ScissorOutlined',
  'DeleteOutlined',
  'SnippetsOutlined',
  'DiffOutlined',
  'HighlightOutlined',
  'AlignCenterOutlined',
  'AlignLeftOutlined',
  'AlignRightOutlined',
  'BgColorsOutlined',
  'BoldOutlined',
  'ItalicOutlined',
  'UnderlineOutlined',
  'StrikethroughOutlined',
  'RedoOutlined',
  'UndoOutlined',
  'ZoomInOutlined',
  'ZoomOutOutlined',
  'FontColorsOutlined',
  'FontSizeOutlined',
  'LineHeightOutlined',
  'DashOutlined',
  'SmallDashOutlined',
  'SortAscendingOutlined',
  'SortDescendingOutlined',
  'DragOutlined',
  'OrderedListOutlined',
  'UnorderedListOutlined',
  'RadiusSettingOutlined',
  'ColumnWidthOutlined',
  'ColumnHeightOutlined'
];

// 数据图标
const dataIcons = [
  'AreaChartOutlined',
  'PieChartOutlined',
  'BarChartOutlined',
  'DotChartOutlined',
  'LineChartOutlined',
  'RadarChartOutlined',
  'HeatMapOutlined',
  'FallOutlined',
  'RiseOutlined',
  'StockOutlined',
  'BoxPlotOutlined',
  'FundOutlined',
  'SlidersOutlined'
];

// 品牌图标
const brandIcons = [
  'AndroidOutlined',
  'AppleOutlined',
  'WindowsOutlined',
  'IeOutlined',
  'ChromeOutlined',
  'GithubOutlined',
  'AliwangwangOutlined',
  'DingdingOutlined',
  'WeiboSquareOutlined',
  'WeiboCircleOutlined',
  'TaobaoCircleOutlined',
  'Html5Outlined',
  'WeiboOutlined',
  'TwitterOutlined',
  'WechatOutlined',
  'YoutubeOutlined',
  'AlipayCircleOutlined',
  'TaobaoOutlined',
  'SkypeOutlined',
  'QqOutlined',
  'MediumWorkmarkOutlined',
  'GitlabOutlined',
  'MediumOutlined',
  'LinkedinOutlined',
  'GooglePlusOutlined',
  'DropboxOutlined',
  'FacebookOutlined',
  'CodepenOutlined',
  'CodeSandboxOutlined',
  'AmazonOutlined',
  'GoogleOutlined',
  'CodepenCircleOutlined',
  'AlipayOutlined',
  'AntDesignOutlined',
  'AntCloudOutlined',
  'AliyunOutlined',
  'ZhihuOutlined',
  'SlackOutlined',
  'SlackSquareOutlined',
  'BehanceOutlined',
  'BehanceSquareOutlined',
  'DribbbleOutlined',
  'DribbbleSquareOutlined',
  'InstagramOutlined',
  'YuqueOutlined',
  'AlibabaOutlined',
  'YahooOutlined',
  'RedditOutlined',
  'SketchOutlined',
  'WhatsAppOutlined',
  'DingtalkOutlined'
];

// 应用图标
const applicationIcons = [
  'AccountBookOutlined',
  'AimOutlined',
  'AlertOutlined',
  'ApartmentOutlined',
  'ApiOutlined',
  'AppstoreAddOutlined',
  'AppstoreOutlined',
  'AudioOutlined',
  'AudioMutedOutlined',
  'AuditOutlined',
  'BankOutlined',
  'BarcodeOutlined',
  'BarsOutlined',
  'BellOutlined',
  'BlockOutlined',
  'BookOutlined',
  'BorderOutlined',
  'BranchesOutlined',
  'BugOutlined',
  'BuildOutlined',
  'BulbOutlined',
  'CalculatorOutlined',
  'CalendarOutlined',
  'CameraOutlined',
  'CarOutlined',
  'CarryOutOutlined',
  'CiCircleOutlined',
  'CiOutlined',
  'ClearOutlined',
  'CloudDownloadOutlined',
  'CloudOutlined',
  'CloudServerOutlined',
  'CloudSyncOutlined',
  'CloudUploadOutlined',
  'ClusterOutlined'
];

// 常用图标列表
const commonIcons = [
  'HomeOutlined',
  'SettingOutlined',
  'UserOutlined',
  'TeamOutlined',
  'FileOutlined',
  'FolderOutlined',
  'MenuOutlined',
  'AppstoreOutlined',
  'DashboardOutlined',
  'DatabaseOutlined',
  'CloudOutlined',
  'CodeOutlined',
  'BugOutlined',
  'EditOutlined',
  'DeleteOutlined',
  'PlusOutlined',
  'SearchOutlined',
  'EyeOutlined',
  'LockOutlined',
  'UnlockOutlined',
  ...applicationIcons.slice(0, 5)
];

const allIcons = {
  常用图标: commonIcons,
  方向图标: directionIcons,
  建议图标: suggestionIcons,
  编辑器图标: editorIcons,
  数据图标: dataIcons,
  品牌图标: brandIcons,
  应用图标: applicationIcons
};

const IconSelector = ({ value, onChange }) => {
  const [visible, setVisible] = useState(false);
  const [searchValue, setSearchValue] = useState('');
  const [filteredIcons, setFilteredIcons] = useState(commonIcons);
  const darkTheme = useSelector(state => state.theme.darkTheme);

  const showModal = () => {
    setVisible(true);
  };

  const handleOk = () => {
    setVisible(false);
  };

  const handleCancel = () => {
    setVisible(false);
  };

  const handleIconSelect = (iconName) => {
    onChange && onChange(iconName);
    setVisible(false);
  };

  const handleSearch = (value) => {
    setSearchValue(value);
    if (!value) {
      setFilteredIcons(commonIcons);
      return;
    }
    
    const allIconNames = Object.values(allIcons).flat();
    const filtered = [...new Set(allIconNames.filter(iconName => 
      iconName.toLowerCase().includes(value.toLowerCase())
    ))];
    setFilteredIcons(filtered);
  };

  const tabItems = Object.keys(allIcons).map(category => ({
    key: category,
    label: category,
    children: (
      <List
        grid={{ column: 8 }}
        dataSource={allIcons[category]}
        renderItem={iconName => (
          <List.Item 
            style={{ 
              textAlign: 'center', 
              cursor: 'pointer',
              padding: '8px',
              transition: 'all 0.3s',
              borderRadius: '4px'
            }}
            onClick={() => handleIconSelect(iconName)}
            onMouseEnter={(e) => {
              e.currentTarget.style.backgroundColor = darkTheme ? 'rgba(255, 255, 255, 0.08)' : '#f0f0f0';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.backgroundColor = 'transparent';
            }}
          >
            <div>
              <div style={{ fontSize: '24px', padding: '8px' }}>
                <DynamicIcon iconName={iconName} />
              </div>
              <div style={{ fontSize: '12px', marginTop: '4px' }}>
                {iconName.replace(/(Outlined|Filled|TwoTone)$/, '')}
              </div>
            </div>
          </List.Item>
        )}
      />
    )
  }));

  return (
    <>
      <Input
        value={value}
        onChange={(e) => onChange && onChange(e.target.value)}
        placeholder="请选择菜单图标"
        readOnly
        onClick={showModal}
        suffix={
          value ? (
            <DynamicIcon iconName={value} />
          ) : (
            <Icons.SearchOutlined />
          )
        }
      />
      <Modal
        title="选择图标"
        open={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        width={800}
        okButtonProps={{ style: { display: 'none' } }}
      >
        <Search
          allowClear
          placeholder="搜索图标..."
          value={searchValue}
          onChange={(e) => handleSearch(e.target.value)}
          style={{ marginBottom: '16px' }}
        />
        {searchValue ? (
          <div>
            <h4>搜索结果</h4>
            <List
              grid={{ column: 8 }}
              dataSource={filteredIcons}
              renderItem={iconName => (
                <List.Item 
                  style={{ 
                    textAlign: 'center', 
                    cursor: 'pointer',
                    padding: '8px',
                    transition: 'all 0.3s',
                    borderRadius: '4px'
                  }}
                  onClick={() => handleIconSelect(iconName)}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.backgroundColor = darkTheme ? 'rgba(255, 255, 255, 0.08)' : '#f0f0f0';
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.backgroundColor = 'transparent';
                  }}
                >
                  <div>
                    <div style={{ fontSize: '24px', padding: '8px' }}>
                      <DynamicIcon iconName={iconName} />
                    </div>
                    <div style={{ fontSize: '12px', marginTop: '4px' }}>
                      {iconName.replace(/(Outlined|Filled|TwoTone)$/, '')}
                    </div>
                  </div>
                </List.Item>
              )}
            />
          </div>
        ) : (
          <Tabs 
            defaultActiveKey="常用图标" 
            items={tabItems}
            tabBarGutter={20}
          />
        )}
      </Modal>
    </>
  );
};

export default IconSelector;